#include "startwindow.h"
#include "gamewindow.h"
#include <QPushButton>
#include "startwindow.h"
#include "gamewindow.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFile>
#include <QDebug>
#include <QMessageBox>
#include<QApplication>
#include<QLabel>

StartWindow::StartWindow(QWidget *parent)
    : QMainWindow(parent),
    characters({
        {":/images/resource/images/player.png", ":/images/resource/images/jumpplayer.png"},
        {":/images/resource/images/player2.png", ":/images/resource/images/jumpplayer2.png"}
    })
{
    // ==== 窗口基础设置 ====
    setFixedSize(800, 400);

    // ==== 中央部件初始化 ====
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

    // ==== 角色选择组件 ====
    charImageLabel = new QLabel(this);
    charImageLabel->setFixedSize(100, 100);
    updateCharacterDisplay();

    QLabel *charTitle = new QLabel("选择角色", this);
    charTitle->setStyleSheet("font-size: 24px; color: white;");

    prevBtn = new QPushButton("<", this);
    nextBtn = new QPushButton(">", this);
    prevBtn->setFixedSize(30, 30);
    nextBtn->setFixedSize(30, 30);

    // ==== 按钮样式 ====
    QString btnStyle = "QPushButton {"
                       "background-color: rgba(255,255,255,100);"
                       "border-radius: 15px;"
                       "color: white;"
                       "}";
    prevBtn->setStyleSheet(btnStyle);
    nextBtn->setStyleSheet(btnStyle);

    // ==== 布局设置 ====
    QHBoxLayout *charLayout = new QHBoxLayout();
    charLayout->addWidget(prevBtn);
    charLayout->addWidget(charImageLabel);
    charLayout->addWidget(nextBtn);

    QVBoxLayout *charSelectLayout = new QVBoxLayout();
    charSelectLayout->addWidget(charTitle, 0, Qt::AlignCenter);
    charSelectLayout->addLayout(charLayout);

    // ==== 游戏按钮 ====
    startButton = new QPushButton("开始游戏", this);
    QPushButton *exitButton = new QPushButton("退出游戏", this);
    startButton->setFixedSize(200, 50);
    exitButton->setFixedSize(200, 50);
    startButton->setStyleSheet("font-size: 24px; background-color: #7ebea5; color: white; border-radius: 10px;");
    exitButton->setStyleSheet("font-size: 24px; background-color: #ee836f; color: white; border-radius: 10px;");

    // ==== 主布局 ====
    mainLayout->addStretch();
    mainLayout->addLayout(charSelectLayout);
    mainLayout->addSpacing(30);
    mainLayout->addWidget(startButton, 0, Qt::AlignCenter);
    mainLayout->addWidget(exitButton, 0, Qt::AlignCenter);
    mainLayout->addStretch();

    // ==== 背景和音频 ====
    setBackground();
    validateResources();

    // ==== 信号连接 ====
    connect(startButton, &QPushButton::clicked, this, &StartWindow::startGame);
    connect(exitButton, &QPushButton::clicked, qApp, &QApplication::quit);
    connect(prevBtn, &QPushButton::clicked, this, &StartWindow::prevCharacter);
    connect(nextBtn, &QPushButton::clicked, this, &StartWindow::nextCharacter);
}

StartWindow::~StartWindow() {
    if(backgroundMusic) {
        backgroundMusic->stop();
        delete backgroundMusic;
    }
    delete backgroundOutput;
}

// ==== 关键修改点 1：资源预验证 ====
void StartWindow::validateResources() {
    for (const auto &character : characters) {
        if (!QFile::exists(character.first) || !QFile::exists(character.second)) {
            QMessageBox::critical(this, "资源错误",
                                  QString("角色资源缺失！\n普通状态: %1\n跳跃状态: %2")
                                      .arg(character.first)
                                      .arg(character.second));
            qApp->quit();
        }
    }
}

// ==== 关键修改点 2：安全的角色切换 ====
void StartWindow::prevCharacter() {
    currentCharIndex = (currentCharIndex - 1 + MAX_CHARACTERS) % MAX_CHARACTERS;
    updateCharacterDisplay();
}

void StartWindow::nextCharacter() {
    currentCharIndex = (currentCharIndex + 1) % MAX_CHARACTERS;
    updateCharacterDisplay();
}

void StartWindow::updateCharacterDisplay() {
    auto loadImage = [](const QString& path) {
        QPixmap pix;
        if(pix.load(path)) {
            return pix.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        }
        qWarning() << "加载角色图片失败:" << path;
        QPixmap fallback(100, 100);
        fallback.fill(Qt::red);
        return fallback;
    };

    charImageLabel->setPixmap(loadImage(characters[currentCharIndex].first));
    charImageLabel->setStyleSheet("background: rgba(255,255,255,50); border-radius: 10px;");
}

// ==== 关键修改点 3：安全启动游戏 ====
void StartWindow::startGame() {
    // 最终索引验证
    if(currentCharIndex < 0 || currentCharIndex >= MAX_CHARACTERS) {
        QMessageBox::critical(this, "错误", "无效的角色索引");
        return;
    }

    // 二次资源检查
    const auto &character = characters[currentCharIndex];
    if (!QFile::exists(character.first) || !QFile::exists(character.second)) {
        QMessageBox::critical(this, "资源错误", "角色资源已丢失！");
        return;
    }

    // 创建游戏窗口
    GameWindow *game = new GameWindow(currentCharIndex);
    game->setAttribute(Qt::WA_DeleteOnClose);
    emit startGameRequested(currentCharIndex);


    // 窗口关闭时清理资源
    connect(game, &GameWindow::destroyed, this, [this](){
        this->deleteLater();
        qApp->quit(); // 完全退出程序
    });

    this->hide();
    if(backgroundMusic) backgroundMusic->stop();
    game->show();
}

// ==== 背景设置 ====
void StartWindow::setBackground() {
    QPixmap bg(":/images/resource/images/start-bg.png");
    if(bg.isNull()) {
        qWarning() << "启动背景图加载失败";
        return;
    }

    bg = bg.scaled(size(), Qt::KeepAspectRatioByExpanding);
    QPalette palette;
    palette.setBrush(QPalette::Window, bg);
    setPalette(palette);

    // 背景音乐初始化
    backgroundOutput = new QAudioOutput(this);
    backgroundOutput->setVolume(0.3);

    backgroundMusic = new QMediaPlayer(this);
    backgroundMusic->setAudioOutput(backgroundOutput);
    backgroundMusic->setSource(QUrl("qrc:/images/resource/sounds/gamestart.mp3"));

    if(backgroundMusic->source().isEmpty()) {
        qWarning() << "背景音乐加载失败";
    } else {
        backgroundMusic->setLoops(QMediaPlayer::Infinite);
        backgroundMusic->play();
    }
}
